/*
 * ActivityTable.java
 * 
 * Created on Oct 28, 2007, 12:14:31 PM
 * 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package procrastinator.table;

import procrastinator.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author alex
 */
public class ActivityTable extends AbstractTableModel {
    public static class Period {
        public Date from, to;

        public Period(Date from, Date to) {
            this.from = from;
            this.to = to;
        }
        
        public int duration() {
            return (int) ((to.getTime() - from.getTime())/60000); // duration in minutes
        }
        
    }

    private static final String columnNames[] = {"Time", "Activity", "Category"};
    private static final Class columnClasses[] = {Period.class, String.class, String.class};
    private static final boolean isColumnEditable[] = {false, true, true};
    private List<Activity> rows;
    private DatabaseConnection db;

    public ActivityTable(DatabaseConnection db) {
        rows = new ArrayList<Activity>();
        this.db = db;
        
        

        initWithRecentActivities();
    }

    public void addRow(Date from, Date to, String activity, String category) {
        rows.add(new Activity(from, to, activity, category));
        db.addActivity(from, to, activity, category);

        fireTableRowsInserted(getRowCount() - 1, getRowCount() - 1);
    }

    public Activity getRow(int i) {
        return rows.get(i);
    }

    private void initWithRecentActivities() {
        List<Activity> results = db.getRecentActivities(100);
        
        rows.clear();
        
        for( Activity a : results ) {
            rows.add(a);
        }
        
        fireTableRowsInserted(0, results.size()-1);
    }

    // support for TableModel

    @Override
    public int getRowCount() {
        return rows.size();
    }

    @Override
    public int getColumnCount() {
        return 3;
    }

    @Override
    public String getColumnName(int arg0) {
        return columnNames[arg0];
    }

    @Override
    public Class<?> getColumnClass(int arg0) {
        return columnClasses[arg0];
    }

    @Override
    public boolean isCellEditable(int arg0, int arg1) {
        return isColumnEditable[arg1];
    }

    @Override
    public Object getValueAt(int row, int col) {
        switch(col) {
        case 0: return new Period(rows.get(row).getFrom(), rows.get(row).getTo());
        case 1: return rows.get(row).getActivity();
        case 2: return rows.get(row).getCategory();
        }
        
        return null;
    }

    // TODO what if that row doesn't exist yet

    @Override
    public void setValueAt(Object arg0, int arg1, int arg2) {
        rows.get(arg1).setValueAt(arg2, arg0);
    }



}
